import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls
import BNSPlayer
import QtQuick.LocalStorage
import "Utils.js" as Utils

ApplicationWindow {
    visible: true
    title: "BNSPlayer"
    id: rootItem
    width: 1280
    height: 720

    visibility: mainWindow.fullScreenState ? Window.FullScreen : Window.Windowed

    property var synchronizer : null

    MainWindow {
        id: mainWindow
        onOpenVideoFileCommand: (fileUrl) => {
            openVideoFile(fileUrl)
        }

        audioVolume: 1.0

        onAudioVolumeChanged: {
            // 设置并保存新的音量值
            audioPlayer.setVolume(audioVolume)
            Utils.setValue("audioVolume", audioVolume.toString())
        }

        onProgressSliderMoved: (pos) => {
            rootItem.synchronizer.seek(pos)
        }

        onDecoderStateChanged: {
            if(decoderState === "Pausing" && rootItem.synchronizer != null && !rootItem.synchronizer.isPausing()) {
                rootItem.synchronizer.pause()
            }
            else if(decoderState === "Playing") {
                if(rootItem.synchronizer != null && rootItem.synchronizer.isPausing())
                    rootItem.synchronizer.resume()
            }
        }

        Keys.enabled: true
        focus: true

        onPlaySpeedChanged: {
            rootItem.synchronizer.setPresentSpeed(playSpeed)
        }

        StatesPanel {
            x: 10
            y: 50
            z: 100
            id: statesPanel

            Timer {
                interval: 500
                repeat: true
                running: true
                onTriggered: {

                    if(synchronizer == null)
                        return;

                    var videoPTS = videoFrameProvider.currPTS;
                    var audioPTS = synchronizer.clock();
                    var AVDiffer = audioPTS - videoPTS;
                    statesPanel.set("Video PTS", videoPTS.toString());
                    statesPanel.set("Audio PTS", audioPTS.toString());
                    statesPanel.set("AV differ", AVDiffer.toString());
                    statesPanel.set("Video queue", mainDecoder.decodedVideoFrameCount.toString());
                    statesPanel.set("Audio queue", mainDecoder.decodedAudioFrameCount.toString());
                }
            }
        }

        function flushDecPos() {
            decodingPosition = synchronizer.clock()
        }
    }

    VideoFrameProvider {
        id: videoFrameProvider
        frameRenderer: mainWindow.videoRenderer
        decoder: mainDecoder
    }

    AudioPlayer {
        id: audioPlayer
        decoder: mainDecoder
    }

    Decoder {
        id: mainDecoder
    }

    SystemClockSynchronizer {
        id: sysClocker
    }

    Component.onCompleted: {

        // 恢复以前的音量
        var audioVolume = Number(Utils.value("audioVolume"))
        if(audioVolume >= 0 && audioVolume <= 1.0)
            mainWindow.audioVolume = audioVolume

        var lastFile = Utils.value("lastFile")

        console.log("lastFile: ", lastFile)

        // 打开上一次的视频并暂停
        if(lastFile !== "") {
            if(openVideoFile(lastFile) < 0) {
                console.error("Cannot open video file:", lastFile)
                return
            }

            mainWindow.decoderState = "Pausing"
        }
    }

    function openVideoFile(file) {

        if(rootItem.synchronizer != null) {
            rootItem.synchronizer.clockChanged.disconnect(mainWindow.flushDecPos)
            rootItem.synchronizer.stop()
        }

        // 解码器打开文件并设置进度条和时间label
        if(!mainDecoder.start(file)) {
            console.error("Failed to open file: ", file)
            return -1
        }

        mainDecoder.dumpMediaInformation()

        console.log("Start decoding the file: ", file)
        console.log("The file duration: ", mainDecoder.fileDuration())

        mainWindow.decoderState = "Playing"
        mainWindow.decodingDuration = mainDecoder.fileDuration()

        // 记录为最后一次播放的文件
        Utils.setValue("lastFile", file.toString())
        mainWindow.fileURL = new URL(file);

        mainWindow.decoderState = "Playing"

        if(mainDecoder.nbAudioStreams >= 1) {
            rootItem.synchronizer = audioPlayer
        }
        else {
            rootItem.synchronizer = sysClocker
        }

        videoFrameProvider.synchronizer = rootItem.synchronizer
        rootItem.synchronizer.clockChanged.connect(mainWindow.flushDecPos)
        rootItem.synchronizer.start()

        // 从播放历史中获取该文件最后的播放时间点
        var timepoint = Utils.playHistory(file.toString())
        if(timepoint === undefined || Math.abs(timepoint - 0) < 0.001) {
            console.log("The file is played for the first time")
            return 0
        }

        mainWindow.decodingPosition = timepoint
        rootItem.synchronizer.seek(timepoint)

        return timepoint
    }
}



